package com.yang.service.impl;



import com.yang.domain.dto.UserDTO;
import com.yang.domain.entity.Follow;

import com.yang.mapper.FollowMapper;
import com.yang.mapper.UserMapper;
import com.yang.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.yang.constants.RedisConstants.FOLLOWS_KEY;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yang
 * @since 2022-10-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private FollowMapper followMapper;
    @Resource
    private UserMapper userMapper;


    @Override
    public void follow(Long followUserId, Boolean isFollow) {
        Long userId = UserHolder.getUser().getId();
        String key = FOLLOWS_KEY + userId;
        if (isFollow){
            stringRedisTemplate.opsForSet().add(key,followUserId.toString());
        }else{
            stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
        }
    }

    @Override
    public boolean isFollow(Long followUserId) {

        Long userId = UserHolder.getUser().getId();

        String key = FOLLOWS_KEY + followUserId;

        Boolean isFollow = stringRedisTemplate.opsForSet().isMember(key, userId);

        return Boolean.TRUE.equals(isFollow);
    }

    @Override
    public List<UserDTO> followCommons(Long followUserId) {
        Long userId = UserHolder.getUser().getId();

        String key1 = FOLLOWS_KEY + userId;
        String key2 = FOLLOWS_KEY + followUserId;

        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);

        if (intersect == null || intersect.isEmpty()){
            return Collections.emptyList();
        }

        List<Long> userIdList = intersect.stream().map(Long::valueOf).collect(Collectors.toList());

        return userMapper.selectUsersById(userIdList);
    }
}
